package org.safa.stats.interfaces;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.safa.stats.Statistics;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;



public class StatisticsInterface extends HttpServlet {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Statistics s = Statistics.INSTANCE;

		/**
		 * servlet get operation
		 */
		public void doGet(HttpServletRequest request,
	            			HttpServletResponse response) throws ServletException, IOException {
			
			
			// get input params
			String op = request.getParameter("op");
			
			if(op.equals("reset"))
			{
				//reset stats
				s.resetStats();
			} else if (op.equals("clear"))
			{
				//TODO implement clearing all stats
			}
			 
			String rsp = null;
			
			HashMap<String,HashMap<String,Double>> statsHM = new HashMap<String,HashMap<String,Double>>();
			statsHM = s.getStats();
			
			XStream xStream = new XStream(new DomDriver());
			xStream.alias("map", java.util.Map.class);
			String xml = xStream.toXML(statsHM);
			//
			rsp=xml;
			
			// send a response
			PrintWriter out = response.getWriter();
			out.write("op: " + op + "|" + rsp);
			
		}
		
		
		
		public void doPost(HttpServletRequest request,
	            			HttpServletResponse response) throws ServletException, IOException {
			//TODO update statistics
			// make one "op" to update multiple statistics .... 
			
			
			// get input params
			String op = request.getParameter("op");
			
			HashMap<String,String> hdrs = getHeaders(request);
			String name = hdrs.get("name");
			String value = hdrs.get("value");
			String rsp = null;
			
			if(op.equals("update") && !name.isEmpty() && !value.isEmpty())
			{
				s.updateStatistic(name, Double.valueOf(value));
				rsp = "OK-PUT-" + name + "=" + value;
			}
			
			
			// send a response
			PrintWriter out = response.getWriter();
			out.write("op: " + op + "|" + rsp);
		}
		private HashMap<String, String> getHeaders(HttpServletRequest request) {
			HashMap<String, String> headers = new HashMap<String, String>();
			Enumeration<String> headerNames = request.getHeaderNames();
		    while(headerNames.hasMoreElements()) {
		    	String name = headerNames.nextElement();
		    	
		    		headers.put(name, request.getHeader(name));
		    	
		    }
		    
		   
		    
		    return headers;
		}
	
}
